/*
 * @Author: your name
 * @Date: 2021-05-12 10:38:09
 * @LastEditTime: 2021-05-25 09:16:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vite-project/src/store/modules/user.ts
 */

import { defineStore } from 'pinia';
import { store } from '@/store';
import { createStorage } from '@/utils/Storage';

import { RoleEnum } from '@/enums/roleEnum';

import { loginApi, getUserInfoById } from '@/api/user/user';
import { CURRENT_USER, ACCESS_TOKEN, ROLE_LIST } from '../mutation-types';
import {
    LoginParams,
    GetUserInfoByUserIdParams,
    RoleInfo,
} from '@/api/user/userModel';
import router from '@/router';

const Storage = createStorage({ storage: sessionStorage });

interface UserState {
    token?: string;
    userInfo: object;
    roleList: RoleEnum[];
}

export const useUserStore = defineStore({
    id: 'app-user',
    state: (): UserState => ({
        token: undefined,
        userInfo: {},
        roleList: [],
    }),
    getters: {
        getUserInfo(): object {
            return this.userInfo || Storage.get(CURRENT_USER, {});
        },
        getToken(): string {
            return this.token || Storage.get(ACCESS_TOKEN);
        },
        getRoleList(): RoleEnum[] {
            return this.roleList.length > 0
                ? this.roleList
                : Storage.get(ROLE_LIST);
        },
    },
    actions: {
        setUserInfo(info: object) {
            this.userInfo = info;
            Storage.set(CURRENT_USER, info);
        },
        setToken(token: string, ex: number) {
            this.token = token;
            Storage.set(ACCESS_TOKEN, token);
        },
        setRoleList(roleList: RoleEnum[]) {
            this.roleList = roleList;
            Storage.set(ROLE_LIST, roleList);
        },
        async login(params: LoginParams) {
            try {
                const response = await loginApi(params);
                const { result, code, token } = response;
                if (code == 0) {
                    const ex = 30 * 60 * 1000;
                    this.setToken(token, ex);
                    const userId = result.userId;
                    const userInfo = await this.getUserInfo({ userId });
                    await router.replace('/dashboard');
                    return userInfo;
                }
            } catch (e) {
                return null;
            }
        },
        async getUserInfo({ userId }: GetUserInfoByUserIdParams) {
            const userInfo = await getUserInfoById({ userId });
            const { roles } = userInfo;
            const roleList = roles.map(
                (item: RoleInfo) => item.value
            ) as RoleEnum[];
            this.setUserInfo(userInfo);
            this.setRoleList(roleList);
            return userInfo;
        },
    },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
    return useUserStore(store);
}
